package com.hedl.practice.diyJava.io.study_file.test;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

public class StudyFile {
    public static void main(String[] args) throws IOException {
        //File file = new File("/Users/a101/idea/like.txt");
        File file = new File("..");
        System.out.println(file);       //直接返回  ..
        System.out.println(file.getPath());     //返回实际传入的路径 ..
        System.out.println(file.getAbsoluteFile());     //返回绝对路径    /Users/a101/Java-Project/study/..
        System.out.println(file.getCanonicalFile());    //返回规范路径    /Users/a101/Java-Project

        System.out.println("查看当前系统是执行那种分隔符'\\'或'/'："+File.separator);

        System.out.println("==============================文件和目录===============================");
        File f1 = new File("/Users/a101/idea");
        File f2 = new File("/Users/a101/idea/like.txt");

        System.out.println("判断f1是否有文件："+f1.isFile());       //false
        System.out.println("判断f1是否有目录："+f1.isDirectory());  //true
        System.out.println("判断f2是否有文件："+f2.isFile());       //true
        System.out.println("判断f2是否有目录："+f2.isDirectory());      //false

        System.out.println("判断文件是否可读："+f2.canRead());       //true
        System.out.println("判断文件是否可写："+f2.canWrite());      //true
        System.out.println("判断文件是否可执行："+f2.canExecute());       //false
        System.out.println("判断文件字节大小："+f2.length());        //11

        System.out.println("==============================遍历文件和目录===============================");

        File f3 = new File("/Users/a101/idea");
        File[] fs1 = f3.listFiles();        //列出所有文件和子目录
        printFiles(fs1);
        System.out.println("一下是筛选过后的文件不包括目录，后缀为.txt");
        File[] fs2 = f3.listFiles(new FilenameFilter() {      //文件筛选，仅列出.txt文件
            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(".txt");       //返回true表示接受该文件
            }
        });
        printFiles(fs2);

    }

    private static void printFiles(File[] fs1) {
        System.out.println("====================");
        if (fs1 != null){
            for (File f:fs1){
                System.out.println(f);
            }
        }
        System.out.println("+====================");

        System.out.println("============================Path对象，它位于java.nio.file包=================================");
        Path p1 = Paths.get(".","project","study");     //构造一个Path对象
        System.out.println(p1);

        Path p2 = p1.toAbsolutePath();      //转换为绝对路径
        System.out.println(p2);

        Path p3 = p2.normalize();       //转换为规范路径
        System.out.println(p3);

        File f4 = p3.toFile();      //转换为File对象
        System.out.println(f4);
        for (Path p:Paths.get("..").toAbsolutePath()){      // 可以直接遍历Path
            System.out.println("  "+p);
        }
    }
}
